package com.n9.buymsg.event;

import com.n9.buymsg.AppContext;
import com.n9.buymsg.service.qqonline.NineIPFactory;
import com.n9.buymsg.service.qqonline.QQService;
import com.n9.buymsg.view.MainForm;
import com.n9.buymsg.view.vo.QqVo;
import com.n9.qq.util.VFCodeForm;
import com.n9.sdk.NineIP;
import com.n9.sdk.model.PurchaseKeyword;
import com.n9.sdk.model.UserInfo;
import com.n9.sdk.response.DefaultResponse;
import org.apache.commons.lang3.ArrayUtils;
import org.apache.commons.lang3.StringUtils;
import org.apache.commons.lang3.reflect.MethodUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import java.io.IOException;
import java.lang.reflect.Method;
import java.util.*;
import java.util.concurrent.ConcurrentHashMap;
import java.util.concurrent.Executor;
import java.util.concurrent.ScheduledThreadPoolExecutor;

/**
 * 事件处理器
 * @Author: ice
 * @Date: 2020-06-24 9:39
 */
public class EventProcessor {
    private static final Logger LOGGER = LoggerFactory.getLogger(EventProcessor.class);

    private static final Map<String, Method> ACT_METHOD = new ConcurrentHashMap<>();
    static {
        loadActMethods();
    }

    private static final Executor EXECUTOR = new ScheduledThreadPoolExecutor(5);

    /**
     * 初始化加载ActMapper的注解配置
     */
    private static void loadActMethods() {
        List<Method> methods = MethodUtils.getMethodsListWithAnnotation(EventProcessor.class, EventMapper.class, false, true);
        methods.forEach(m -> {
            EventMapper eventMapper = m.getAnnotation(EventMapper.class);
            String mapperValue = eventMapper.value();
            if (ACT_METHOD.containsKey(mapperValue)) {
                String msg = String.format("eventMapper重复:%s", mapperValue);
                LOGGER.error(msg);
                throw new RuntimeException(msg);
            }
            ACT_METHOD.put(mapperValue, m);
        });
    }

    public void process(AppEvent event) {
        process(event, null);
    }

    public void process(AppEvent event, Callback callback) {
        String actionName = event.getName();
        if (StringUtils.isBlank(actionName)) {
            return;
        }

        Method method = ACT_METHOD.get(actionName);
        if (Objects.nonNull(method)) {

            if (event.isSynchronizeFlag()) {
                processInternal(method, event, callback);
            } else {
                EXECUTOR.execute(()->processInternal(method, event, callback));
            }
        } else {
            String msg = String.format("%s对应匹配到对应的方法", actionName);
            LOGGER.error(msg);
            throw new RuntimeException(msg);
        }
    }

    private void processInternal(Method method, AppEvent event, Callback callback) {
        try {
            Class<?>[] parameterTypes = method.getParameterTypes();
            Object[] params = new Object[parameterTypes.length];
            for (int i = 0; i < parameterTypes.length; i++) {
                Class<?> type = parameterTypes[i];

                Object param = null;
                if (AppEvent.class.isAssignableFrom(type)) {
                    param = event;
                } else if (Callback.class.isAssignableFrom(type)) {
                    param = callback;
                } else {
                    //待扩展,目前暂设null
                    param = null;
                }

                params[i] = param;
            }

            method.invoke(this, params);
        } catch (Exception e) {
            e.printStackTrace();
            LOGGER.error(e.getMessage());
        }
    }


    @EventMapper(AppEvent.LOGIN_FORM_LOGIN)
    private void loginFormLogin(LoginEvent loginEvent) {
        DefaultResponse<String> loginResp = NineIPFactory.create().login(loginEvent.getAccount(), loginEvent.getPassword());
        boolean result = loginResp.isOk();
        if (result) {
            loginEvent.getSource().setVisible(false);
            MainForm.getInstance().setVisible(true);
        } else {
           loginEvent.getSource().showErrorDialog("登陆失败", loginResp.getMsg());
        }
    }

    /**
     * 登陆窗口设置默认值
     * @param loginFormCreateEvent
     */
    @EventMapper(AppEvent.LOGIN_FORM_INIT)
    private void loginFormSetDefault(LoginFormInitEvent loginFormCreateEvent) {
        AppContext context = AppContext.getInstance();
        loginFormCreateEvent.getSource().setAccountAndPassword(context.getAccount(), context.getPassword());
    }

    @EventMapper(AppEvent.MAIN_FORM_INIT)
    private void mainFormInit(MainFormInitEvent mainFormInitEvent, Callback callback) {
        MainForm mainForm = mainFormInitEvent.getSource();
        mainForm.showLog("========数据初始化中========");

        NineIP nineIP = NineIPFactory.create();
        DefaultResponse<UserInfo> userInfoResp = null;
        try {
            userInfoResp = nineIP.getUserInfo();
        } catch (IOException e) {
            e.printStackTrace();
        }
        if (!userInfoResp.isOk()) {
            mainForm.showLog("获取QQ账号信息失败");
            return;
        }

        UserInfo userInfo = userInfoResp.getData();
        List<Map<String, String>> qqAccountPair = userInfo.getQqAccountPair();
        if (Objects.isNull(qqAccountPair) || qqAccountPair.isEmpty()) {
            mainForm.showLog("尚未在管理后台设置QQ账号,无法使用软件");
            return;
        }
        qqAccountPair.forEach((map) -> {
            Map.Entry<String, String> next = map.entrySet().iterator().next();
            if (Objects.nonNull(next)) {
                QqVo qqVo = new QqVo(Long.parseLong(next.getKey()), next.getValue());
                mainForm.addQQVos(qqVo);
            }
        });
        mainForm.showLog("获取QQ账号信息成功");

        DefaultResponse<PurchaseKeyword> resp = nineIP.fetchKeywords();
        if (!resp.isOk()) {
            mainForm.showLog("获取求购信息关键词失败");
            return;
        }

        PurchaseKeyword keyword = resp.getData();
        String[] keywords = getKeywordsArray(keyword);
        AppContext.getInstance().initMsgBodyFilter(keywords);
        mainForm.showLog("获取求购信息关键词成功:" + keyword.getGlobalKeywords());

        callback.call();
    }

    private String[] getKeywordsArray(PurchaseKeyword keyword) {
        String[] keywords = new String[0];
        if(Objects.isNull(keyword)) {
            return keywords;
        }
        String separator = ",|，";


        if (StringUtils.isNotEmpty(keyword.getGlobalKeywords())) {
            String[] split = keyword.getGlobalKeywords().split(separator);
            keywords = ArrayUtils.addAll(keywords, split);
        }

        if (StringUtils.isNotEmpty(keyword.getKeywords())) {
            String[] split = keyword.getGlobalKeywords().split(separator);
            keywords = ArrayUtils.addAll(keywords, split);
        }
        return keywords;
    }

    @EventMapper(AppEvent.MAIN_FORM_EXTRACT_START)
    private void mainFormStartBtn(ExtractStartEvent extractStartEvent) {
        AppContext.getInstance().getQqVos().forEach(qqVo -> {
            new QQService(VFCodeForm.instance()).login(qqVo);
        });
    }

    @EventMapper(AppEvent.LOG_MSG_VIEW)
    private void logMsgView(LogMsgViewEvent event) {
        MainForm.getInstance().showLog(event.getLogMsg());
    }

    @EventMapper(AppEvent.QQ_LOGIN_SUCCESS)
    private void qqLoginSuccess(QQLoginSuccessEvent event) {
        QqVo qqVo = event.getQqVo();
        if (Objects.isNull(qqVo)) {
            return;
        }
        MainForm.getInstance().updateQqVo(qqVo);
    }

    @EventMapper(AppEvent.QQ_NEW_MSG)
    private void onQqNewMsg(QQMsgCountEvent newMsgEvent) {
        MainForm.getInstance().updateQQMsgCount(newMsgEvent.getQqUin(), newMsgEvent.getMsgCount());
    }

    @EventMapper(AppEvent.BUY_MSG_STORE_SUCCESS)
    private void onNewBuyMsg(QQMsgCountEvent newMsgEvent) {
        MainForm.getInstance().updateBuyMsgCount(newMsgEvent.getQqUin(), newMsgEvent.getMsgCount());
    }
}
